<?php
namespace app;

use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
use util\CommonUtil;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    private $code;
    private $msg;
    private $statusCode;
    private $request;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->request = $this->app->request;
    }
    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param  Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request   $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        // 添加自定义异常处理机制
        if($e instanceof HttpResponseException){
            if($this->app->isDebug()) {
                $start_time = $this->app->getBeginTime();
                $start_mem = $this->app->getBeginMem();
                $now_time = microtime(true);
                $now_mem = memory_get_usage();
                $use_time = $now_time - $start_time;
                $use_mem = $now_mem - $start_mem;
                $format_use_time = number_format($use_time, 6) . 's';
                $format_use_mem = CommonUtil::instance()->format_bytes($use_mem);
                $data = $e->getResponse()->getData();
                $data['use_time'] = $format_use_time;
                $data['use_mem'] = $format_use_mem;
                $e->getResponse()->data($data);
            }
        }
        return parent::render($request,$e);
    }
}
